package com.sgb.kjwl.viewmodel.machine;

import android.text.TextUtils;

import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.lease.LeaseListEntity;
import com.sgb.kjwl.model.entity.request.LeaseFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.repository.MachineRepertory;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.fragment.machine.LeaseBusinessFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LeaseBusinessFragmentModel extends BaseViewModel {
    private final LeaseBusinessFragment fragment;
    private final MachineRepertory repertory;
    private int page = 1;
    public int pageSize = 20;

    public LeaseBusinessFragmentModel(LeaseBusinessFragment fragment, MachineRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    public String getAreaNameModel() {
        return repertory.getAreaName();
    }

    public String getAreaCodeModel() {
        return repertory.getAreaCode();
    }

    public void getData(LeaseFilterJson filterJson,boolean isLoadMore) {
        page = isLoadMore ? page + 1 : 1;
        filterJson.setPageNum(page);
        filterJson.setPageSize(pageSize);
        if (repertory.getIsLocal()) {
            //经度
            filterJson.setLatitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""));
            //纬度
            filterJson.setLongitude("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""));
        } else {
            //经度
            filterJson.setLongitude(repertory.getLongititude());
            //纬度
            filterJson.setLatitude(repertory.getLatitude());
        }
        //获取租赁手动定位缓存
        String distance_latitude = SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude", "");
        String distance_longitude = SharedPreferenceUtil.getInstance().getSaveStringData("distance_longitude", "");
        if (!TextUtils.isEmpty(distance_latitude) && !TextUtils.isEmpty(distance_longitude)) {
            filterJson.setLatitude(distance_latitude);
            filterJson.setLongitude(distance_longitude);
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().rentalAndEmployedHall(filterJson).enqueue(new ICallBack<BaseEntity<ListResponse<List<LeaseListEntity>>>>() {

            @Override
            public void onSuccess(BaseEntity<ListResponse<List<LeaseListEntity>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getData() != null) {
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    fragment.showList(new ArrayList<>(), isLoadMore);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<LeaseListEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                fragment.showList(new ArrayList<>(), isLoadMore);
            }
        });
    }

//    //获取类型分类数据
//    public void getTypeModel() {
//        APIManager.getInstance().getMachineAPI().getAllTypeList().enqueue(new ICallBack<BaseEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>>>>(true) {
//
//            @Override
//            public void onSuccess(BaseEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>>> data) {
//                fragment.showTypeView(data.getData());
//            }
//        });
//    }

    //获取租赁类目下的一级分类
    public void getFistCategoryModel(String type) {
        APIManager.getInstance().getLeaseMapAPI().getFistcategory(type).enqueue(new ICallBack<BaseEntity<List<DictEntity3>>>(true) {
            @Override
            public void onSuccess(BaseEntity<List<DictEntity3>> data) {
                fragment.setTabFirst(data.getData());
            }
        });
    }

    //获取租赁类目下的二级分类
    public void getSecondCategoryModel(String type, String parentNo) {
        APIManager.getInstance().getLeaseMapAPI().getSecondcategory(type, parentNo).enqueue(new ICallBack<BaseEntity<List<DictEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<DictEntity3>> data) {
                fragment.setTabSecond(data.getData());
            }
        });
    }

    /**
     * 获取属性筛选列表
     */
    public void getFilterSpec(String categoryNo, String typeNo) {
        APIManager.getInstance().getLeaseAPI().getAttributeList2(categoryNo, typeNo).enqueue(new ICallBack<BaseEntity<List<DictEntity3>>>(true) {
            @Override
            public void onSuccess(BaseEntity<List<DictEntity3>> data) {
                fragment.showFilterSpec(data.getData());
            }
        });
    }

    public void getUrlSetting(String id) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting("competitivePurchase").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id;
                    String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                    String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                    url = url + "&lng=" + lng + "&lat=" + lat;
                    WebViewX5HostActivity.start(fragment.getActivity(), url, id);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 获取省市区地址
     */
    public void getCityData() {
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null && data.size() > 0) {
                    fragment.showAddressDatas(data, repertory.getAreaCode());
                }
            }
        });
    }

    //排序列表
    public void getFilterSort() {
        APIManager.getInstance().getLeaseAPI().getLeaseHomeSortWay().enqueue(new ICallBack<BaseEntity<List<DictEntity3>>>(true) {
            @Override
            public void onSuccess(BaseEntity<List<DictEntity3>> data) {
                fragment.setSortData(data.getData());
            }
        });
    }

    //获取成员会员公司列表
    public void getTypeCompany(int companyType) {
        APIManager.getInstance().getLeaseAPI().getMemberByType(companyType).enqueue(new ICallBack<BaseEntity<List<DictEntity3>>>(true) {
            @Override
            public void onSuccess(BaseEntity<List<DictEntity3>> data) {
                fragment.setTabCompany(data.getData());
            }
        });
    }

    public void getH5Url(String type, String id) {
        String name = "";
        if ("1".equals(type)) {
            name = "mechanicsDetail";//机械
        } else if ("2".equals(type)) {
            name = "equipmentDetails";//设备
        } else if ("3".equals(type)) {
            name = "vehicleDetails";//车辆
        } else if ("4".equals(type)) {
            name = "propertyDetails";//房产
        } else if ("5".equals(type)) {
            name = "landDetails";//土地
        } else if ("6".equals(type)) {
            name = "factoryDetails";//工厂
        } else if ("7".equals(type)) {
            name = "farmDetail";//农机
        }
        if (TextUtils.isEmpty(name)) {
            return;
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(name).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id + "&iosFlag=1";
//                    WebViewX5HostActivity.start(fragment.getActivity(), url);
                    WebViewX5HostActivity.start(fragment.getActivity(), url, id, "lease", type);
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
